﻿using System;
using System.IO;
using System.Net;

namespace AMing.Core.Http
{
    public class HttpHelper
    {
        /// <summary>
        /// HttpGet(异步)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="callback"></param>
        public void Get_Async(string url, Action<string> callback)
        {
            HttpWebRequest request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
            //try
            //{
            request.BeginGetResponse((iar) =>
            {
                //try
                //{
                HttpWebResponse response = request.EndGetResponse(iar) as HttpWebResponse;
                if (response != null)
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            string searchContent = string.Empty;
                            searchContent = sr.ReadToEnd();
                            if (callback != null)
                            {
                                callback(searchContent);
                            }
                        }
                    }
                }
                //}
                //catch
                //{
                //    callback(null);
                //}
            }, null);
            //}
            //catch
            //{
            //    callback(null);
            //}
        }
        /// <summary>
        /// HttpGet
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="callback"></param>
        public string Get(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                request.UserAgent = "WPApps";
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Timeout = 10000;

                WebResponse rep = request.GetResponse();
                using (Stream stream = rep.GetResponseStream())
                using (StreamReader sr = new StreamReader(stream))
                {
                    string content = sr.ReadToEnd();
                    return content;
                }
            }
            catch
            {
                return null;
            }
        }

    }
}
